﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;

namespace CPPEI.Coolzon.UI.XProperty.Converters
{
    public class XColorPlateConverter : IPropertyValueConverter
    {
        public object Convert(ConvertContext context, Metadata.ValueNode valueNode)
        {
            ColorPlate colorPlate = new ColorPlate();
            foreach (Metadata.ValueNode value in valueNode.ValueNodes)
            {
                string colorString = value.Attributes["Color"];
                if (!string.IsNullOrEmpty(colorString))
                {
                    SolidColorBrush scb = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colorString));
                    colorPlate.AddColor(scb);
                }
            }
            return colorPlate;
        }

        public Metadata.ValueNode ConvertBack(ConvertContext context, object value)
        {
            UI.ColorPlate colorPlate = (UI.ColorPlate)value;
            if (colorPlate == null)
            {
                return null;
            }

            Metadata.ValueNode colorPlateRootNode = new Metadata.ValueNode("ColorPlate");
            colorPlateRootNode.Attributes = new Dictionary<string, string>();
            colorPlateRootNode.ValueNodes = new List<Metadata.ValueNode>();
            
            List<Brush> colorList = colorPlate.GetColorList();
            if(colorList != null && colorList.Count > 0)
            {
                for (int index = 0; index < colorList.Count; index++)
                {
                    Metadata.ValueNode vNode = new Metadata.ValueNode("SolidBrush");
                    vNode.Attributes = new Dictionary<string, string>();
                    Color color = (Color)ColorConverter.ConvertFromString(System.Convert.ToString(colorList[index]));
                    string colorString = color.ToString();
                    vNode.Attributes.Add("Color", colorString);
                    colorPlateRootNode.ValueNodes.Add(vNode);
                }
            }

            return colorPlateRootNode;
        }
    }
}
